﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microhard.Permission.Models;
using Microhard.Permission.Interface;
using Microhard.Core;
using Microhard.Framework.MVCHelper;

namespace Microhard.Permission.MVCFilter
{
    public class MVCFilterAtrForResourcePermission : ActionFilterAttribute, IMvcFilter
    {
        private IFuncAuthorization per = IoC.Resolve<IFuncAuthorization>();
        private IUser user = IoC.Resolve<IUser>();

        /// <summary>
        /// 资源标示
        /// </summary>
        public string ResouceKeyName { set; get; }
        /// <summary>
        /// 行为标示
        /// </summary>
        public string OperationKeyName { set; get; }


        public MVCFilterAtrForResourcePermission()
        {
            //表示作为action filter第二个执行
            this.Order = 1;
        }

        #region IMvcFilter Members

        public void RedirectToPage(ActionExecutingContext filterContext)
        {
            string msg = "此模块您没有访问权限，请向管理员申请开放";
            user.SignOut();
            filterContext.HttpContext.Session.Clear();
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    Data = msg
                };
            }
            else
            {
                var ad = new ViewResult();
                ad.ViewName = "AccessDenied";
                filterContext.Controller.ViewData["deniedMsg"] = msg;
                filterContext.Result = ad;
            }
        }

        #endregion

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string actionName = filterContext.ActionDescriptor.ActionName.ToLower();
            string ctrName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
            bool isSysAction = FilterHelper.IsSysAdminAction(filterContext.ActionDescriptor.ControllerDescriptor.ControllerName);
            var currentUser = filterContext.HttpContext.Session["userInfo"] as User;

            //组装验证基本信息
            //如果此资源拥有流程，则添加，删除，修改自动跳转到流程action上
            PermissionRequest pr = new PermissionRequest();
            pr.RequestOperation = new Operation();
            pr.RequestResouce = new Resouce();
            if (string.IsNullOrEmpty(this.OperationKeyName))
            {
                pr.RequestOperation.KeyName = actionName;
            }
            else
            {
                pr.RequestOperation.KeyName = this.OperationKeyName.ToLower();
            }
            if (string.IsNullOrEmpty(this.ResouceKeyName))
            {
                pr.RequestResouce.KeyName = ctrName;
            }
            else
            {
                pr.RequestResouce.KeyName = this.ResouceKeyName.ToLower();
            }
            pr.UserName = currentUser.UserName;

            List<string> hasPms = new List<string>();
            List<Microhard.Permission.Models.Permission> currentPermissions = null;

            //是否拥有功能权限
            if (!per.IsApprove(pr, out hasPms, out currentPermissions))
            {
                this.RedirectToPage(filterContext);
                return;
            }
            else
            {
                //装载到user的session中
                currentUser.Permissions = currentPermissions;
                filterContext.HttpContext.Session["userInfo"] = currentUser;
                //验证通过，把用户对资源的操作赋值到Form Items中，为页面是否创建行为提供依据
                filterContext.HttpContext.Items.Remove(SysConst.OPERATION_ITEM_KEYNAME);
                filterContext.HttpContext.Items.Remove(SysConst.DATACOLLECTION_PERMISSIONID);
                filterContext.HttpContext.Items.Add(SysConst.OPERATION_ITEM_KEYNAME, hasPms);
                filterContext.HttpContext.Items.Add(SysConst.DATACOLLECTION_PERMISSIONID, currentPermissions.Select(p => p.PermissionID).ToList());
            }
        }
    }
}
